import cv2
import mediapipe as mp
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils

class HandTracking():
    def __init__(self):
        self.hand_tracking = mp_hands.Hands()
        self.hand_x = 0
        self.hand_y = 0
        self.results = None
        self.hand_right_close = False
        self.hand_left_close = False
    def scan_hands(self,image):
        #水平翻转并且转为RGB以供检测
        image = cv2.cvtColor(cv2.flip(image,1),cv2.COLOR_BGR2RGB)
        image.flags.writeable = False
        self.results = self.hand_tracking.process(image)

        image.flags.writeable = True
        image = cv2.cvtColor(image,cv2.COLOR_RGB2BGR)

        self.myhands = []
        self.hands_type = []

        self.hand_right_close = False

        if self.results.multi_hand_landmarks:
            #识别左右手
            for hand in self.results.multi_handedness:
                hand_type = hand.classification[0].label
                self.hands_type.append(hand_type)
            #获取坐标
            for hand_landmarks in self.results.multi_hand_landmarks:
                self.myhand = []
                #将坐标存入列表
                for landmark in hand_landmarks.landmark:
                    self.myhand.append((landmark.x*1440,landmark.y*1080))
                self.myhands.append(self.myhand)

                mp_drawing.draw_landmarks(image,hand_landmarks,mp_hands.HAND_CONNECTIONS)
            #判断手掌是否闭合
            for hand,handtype in zip(self.myhands,self.hands_type):
                if handtype == 'Right' and (hand[12][1] > hand[9][1]):
                    self.hand_right_close = True
                elif handtype == 'Right' and (hand[12][1] <= hand[9][1]):
                    self.hand_right_close = False
                elif handtype == 'Left' and (hand[12][1] > hand[9][1]):
                    self.hand_left_close = True
                elif handtype == 'Left' and (hand[12][1] <= hand[9][1]):
                    self.hand_left_close = False
        return image